<template>
    <div class="edit-supplier">
        <div class="header">
            <div class="nav-bar">
                <p class="font16">编辑供应商</p>
                <router-link to="/supplier">
                    <el-button class="back-btn">返回</el-button>
                </router-link>
            </div>
        </div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" style="width:600px">
            <el-form-item label="公司名称" prop="name">
                <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="简称" prop="code">
                <el-input v-model="ruleForm.code"></el-input>
            </el-form-item>
            <el-form-item label="主营业务" prop="business_scope">
                <el-select v-model="ruleForm.business_scope" placeholder="请选择主营业务">
                    <el-option label="原材料供应" value="原材料供应"></el-option>
                    <el-option label="食品加工" value="食品加工"></el-option>
                    <el-option label="包装供应" value="包装供应"></el-option>
                    <el-option label="物流服务" value="物流服务"></el-option>
                    <el-option label="其他" value="其他"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
                <el-input v-model="ruleForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="总部地址" prop="address">
                <el-cascader
                    expand-trigger="hover"
                    :options="options"
                    v-model="selectedOptions"
                    @change="handleAddressChange">
                </el-cascader>
                <el-input v-model="ruleForm.addressDetail" style="margin-top: 10px" placeholder="详细地址"></el-input>
            </el-form-item>
            <el-form-item label="成立时间" prop="found_time">
                <el-date-picker
                    v-model="ruleForm.found_time"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="资质证书" prop="upload">
                <el-upload
                  action="https://jsonplaceholder.typicode.com/posts/"
                  list-type="picture-card"
                  :multiple="true"
                  :on-success="handleUploadSuccess"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove">
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog v-model="dialogVisible" size="tiny">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import axios from 'axios';
    export default {
        data() {
            return {
                supplierId: '',
                ruleForm: {
                    name: '',
                    code: '',
                    business_scope: '',
                    phone: '',
                    address: '',
                    addressDetail: '',
                    found_time: '',
                    certificates: [],
                    status: 'active'
                },
                
                selectedOptions: [],
                
                options: [{
                    value: '北京',
                    label: '北京',
                    children: [{
                        value: '北京市',
                        label: '北京市',
                        children: [{
                            value: '东城区',
                            label: '东城区'
                        }, {
                            value: '西城区',
                            label: '西城区'
                        }]
                    }]
                }, {
                    value: '上海',
                    label: '上海',
                    children: [{
                        value: '上海市',
                        label: '上海市',
                        children: [{
                            value: '黄浦区',
                            label: '黄浦区'
                        }, {
                            value: '徐汇区',
                            label: '徐汇区'
                        }]
                    }]
                }],
                
                dialogImageUrl: '',
                dialogVisible: false,
                
                rules: {
                    name: [{
                        required: true,
                        message: '请输入公司名称',
                        trigger: 'blur'
                    }],
                    code: [{
                        required: true,
                        message: '请输入公司简称',
                        trigger: 'blur'
                    }],
                    business_scope: [{
                        required: true,
                        message: '请选择主营业务',
                        trigger: 'change'
                    }],
                    phone: [{
                        required: true,
                        message: '请输入联系方式',
                        trigger: 'blur'
                    }, {
                        pattern: /^((400|800)-?\d{3}-?\d{4}|0\d{2,3}-?\d{7,8}|1[3-9]\d{9})$/, 
                        message: '请输入正确的联系方式（400/800电话、固话或手机）',
                        trigger: 'blur'
                    }],
                    address: [{
                        required: true,
                        message: '请选择公司地址',
                        trigger: 'change'
                    }],
                    found_time: [{
                        required: true,
                        message: '请选择成立时间',
                        trigger: 'change',
                        type: 'date'
                    }]
                }
            };
        },
        
        created() {
            // 从路由参数获取供应商ID
            this.supplierId = this.$route.query.id;
            if (this.supplierId) {
                this.getSupplierData();
            }
        },
        
        methods: {
            // 获取供应商数据
            getSupplierData() {
                // 实际API调用
                axios.get(`/api/suppliers/${this.supplierId}`)
                .then(response => {
                    if (response.data.status === 'success') {
                        const supplier = response.data.supplier;
                        this.ruleForm = {
                            name: supplier.name || '',
                            code: supplier.code || '',
                            business_scope: supplier.business_scope || '',
                            phone: supplier.phone || '',
                            address: supplier.address || '',
                            addressDetail: '',
                            found_time: supplier.found_time ? new Date(supplier.found_time) : '',
                            status: supplier.status || 'active'
                        };
                        
                        // 处理地址
                        if (supplier.address) {
                            const addressParts = supplier.address.split(' ');
                            if (addressParts.length >= 3) {
                                this.selectedOptions = addressParts.slice(0, 3);
                                this.ruleForm.addressDetail = addressParts.slice(3).join(' ');
                            }
                        }
                    } else {
                        this.$message.error(response.data.message || '获取供应商数据失败');
                    }
                })
                .catch(err => {
                    console.error('获取供应商数据失败:', err);
                    this.$message.error('获取供应商数据失败');
                });
            },
            
            handleAddressChange(value) {
                this.ruleForm.address = value.join(' ');
            },
            
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        // 构建完整地址
                        let fullAddress = '';
                        if (this.selectedOptions && this.selectedOptions.length > 0) {
                            fullAddress = this.selectedOptions.join(' ');
                        }
                        if (this.ruleForm.addressDetail) {
                            fullAddress += ' ' + this.ruleForm.addressDetail;
                        }
                        
                        // 构建要发送的数据
                        const supplierData = {
                            name: this.ruleForm.name,
                            code: this.ruleForm.code,
                            business_scope: this.ruleForm.business_scope,
                            phone: this.ruleForm.phone,
                            address: fullAddress,
                            found_time: this.ruleForm.found_time ? this.formatDate(this.ruleForm.found_time) : null,
                            status: this.ruleForm.status
                        };
                        
                        // 发送数据到服务器
                        axios.put(`/api/suppliers/${this.supplierId}`, supplierData)
                        .then(response => {
                            if (response.data.status === 'success') {
                                this.$message.success('供应商信息更新成功');
                                this.$router.push('/supplier');
                            } else {
                                this.$message.error(response.data.message || '更新失败');
                            }
                        })
                        .catch(err => {
                            if (err.response && err.response.data && err.response.data.message) {
                                this.$message.error(err.response.data.message);
                            } else {
                                console.error('更新供应商数据失败:', err);
                                this.$message.error('更新供应商数据失败');
                            }
                        });
                    } else {
                        console.log('表单验证失败');
                        return false;
                    }
                });
            },
            
            resetForm(formName) {
                this.$refs[formName].resetFields();
                this.getSupplierData();
            },
            
            handleUploadSuccess(response, file, fileList) {
                this.ruleForm.certificates.push({
                    name: file.name,
                    url: URL.createObjectURL(file.raw)
                });
            },
            
            handleRemove(file, fileList) {
                const index = this.ruleForm.certificates.findIndex(item => item.url === file.url);
                if (index !== -1) {
                    this.ruleForm.certificates.splice(index, 1);
                }
            },
            
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            
            formatDate(date) {
                if (!date) return null;
                
                try {
                    if (date instanceof Date) {
                        // 确保是有效日期
                        if (isNaN(date.getTime())) return null;
                        return date.toISOString().split('T')[0]; // 返回YYYY-MM-DD格式
                    }
                    
                    // 如果是字符串，尝试转换
                    const dateObj = new Date(date);
                    if (isNaN(dateObj.getTime())) return date;
                    return dateObj.toISOString().split('T')[0];
                } catch (e) {
                    console.error('日期格式化错误:', e);
                    return null;
                }
            }
        }
    }
</script>

<style scoped>
    .edit-supplier {
        height: calc(100vh - 64px);
        padding: 20px;
        background-color: #fff;
    }
    .header {
        padding: 15px;
        padding-top: 30px;
    }
    .nav-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .back-btn {
        margin-right: 40px;
        width: 100px;
        border-radius: 20px;
    }
</style>